package com.mediacloud.app.newsmodule.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.media.MediaMetadata;
import android.media.session.PlaybackState;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.chinamcloud.audioserver.APSLifecycleKit;
import com.eventTrack.TXReportManager;
import com.jaeger.library.StatusBarUtil;
import com.lzf.easyfloat.permission.PermissionUtils;
import com.mediacloud.app.assembly.util.BitmapUtil;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.ImageButtonX;
import com.mediacloud.app.assembly.views.LikeBadgeView;
import com.mediacloud.app.assembly.widget.SeekBarX;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.model.news.TopicDetailDataReciver;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.comment.x.XCommentActivity;
import com.mediacloud.app.newsmodule.addnewslike.m.AddLikeDataInvoke;
import com.mediacloud.app.newsmodule.addnewslike.p.NewsLikePresenter;
import com.mediacloud.app.newsmodule.addnewslike.v.ILikesNumUpdate;
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils;
import com.mediacloud.app.newsmodule.pay.NormalPayUtil;
import com.mediacloud.app.newsmodule.pay.PaidContentListener;
import com.mediacloud.app.newsmodule.pay.PaidMetas;
import com.mediacloud.app.newsmodule.utils.AppfacBuyEnableUtils;
import com.mediacloud.app.newsmodule.utils.AudioMngHelper;
import com.mediacloud.app.newsmodule.utils.BitmapUtils;
import com.mediacloud.app.newsmodule.utils.BlurTransformation;
import com.mediacloud.app.newsmodule.utils.CollectionController;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.TopicListDataInvoker;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.newsmodule.utils.support.SupportKit;
import com.mediacloud.app.newsmodule.view.CommentDialog;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.reslib.enums.TitileType;
import com.mediacloud.app.reslib.enums.XKey;

import com.tencent.mmkv.MMKV;
import com.utils.SystemServiceManager;
import com.utils.UriTool;
import com.utils.read.AudioFloatManager;
import com.zly.widget.CollapsedTextView;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 音频点直播 的基类 主要是处理了布局  分享等功能
 *
 * @author x
 */
public abstract class BaseAudioActivity extends HandleDataCollectActivity implements OnClickListener, CollectionController.CollectStatusListener, ILikesNumUpdate {

    public static final int AUDIO_STYLE_FULL_SCREEN = 0;
    public static final int AUDIO_STYLE_HALF_SCREEN = 1;
    public boolean chatRoomOpen;
    protected final String REPLAY_MARK_FLAG = "REPLAY_MARK_FLAG";
    /**
     * 音频对象  就是当前播放的 那条新闻
     */
    protected boolean isFirst = true;
    protected boolean isAutoPlay = true;
    protected String url;
    protected String cdnEncrypt;
    protected CatalogItem catalogItem;
//    protected LinearLayout audioInfoContainer;
    /**
     * 半屏才有这个
     */
    View mBottom_shareBtn;
    protected SeekBarX seekbar;
    protected View playBtnContainer, mLoadingView;
    protected RelativeLayout letmeSayLayout;

    protected TextView currentPlayPosition, totoalLength;
    /**
     * 进度条
     */
    protected View progressLayoutView;
    /**
     * 全屏的底部背景，半屏样式没得
     */
    protected ImageView fullImageBottomBg;
    protected RelativeLayout fullRelativeSwitch;
    protected RelativeLayout fullRelativeInfo;
    protected ImageView fullImageGuide;
    protected TextView fullTvGuideInfo;
    protected ProgressBar fullVoiceSeekBar;
    protected AudioMngHelper audioMngHelper;
    protected View fullTopMaskView;


    protected View dotContainer, logoDot, desDot, letmeSay;
    public com.mediacloud.app.assembly.views.BadgeView commentsBadgeView;
    protected ImageButtonX programBtn, loopModeBtn, collectionBtn, togglePauseBtn, prev_audioBtn, next_audioBtn, vodRelevant;
    //    protected appfacAudioDiss audio_like_imageview;
    protected LikeBadgeView likeBadgeView;
    protected TextView streamLineBtn;
    protected TextView audioDesTitle;
    protected CollapsedTextView collapsedTextView;
    protected TextView tvInfoTitle;
    protected ViewGroup componentLinear;
//    protected SharePopGridWindow sharePopWindow;
//    protected ShareGridDataUtil shareGridDataUtil;
    protected  ShareWrap shareWrap;

    // protected BadgeView badgeView;

    boolean loadedImg;
    NewsLikePresenter newsLikePresenter;
    protected boolean openLikeBtn;
    protected ImageView mBgImage;
    protected final int TYPE_NO_NETWORK = 0;// 無網絡
    protected final int TYPE_NOT_WIFI = 1; //不是WIFI
    protected Dialog dialog;
    protected int dialogType = -1;


    protected int audioStyle;

    private CollectionController collectionController;
    //    CommentPopupWindow commentDialogFram;
    protected TopicListDataInvoker topicListDataInvoker;
    protected int pageNum = 1;
    protected int pageSize = 15;
    private ImageView newTitleBgImage, imageToggleBg;
    private BitmapDrawable newTitleBitmapDrawable;
    private TextView tv_audio_title;
    /**
     * 全屏的音频简介是否显示
     */
    private boolean relativeInfoShow;
    long startLong = 0L;
    long endLong = 0L;
    public LinearLayout broccoliLayout;
    public ShowSwitch showSwitch;
    public int bgColorFromBitmap = Color.RED;


    protected APSLifecycleKit apsKit;

    private void initAPS() {
        apsKit = new APSLifecycleKit(this, "" + articleItem.getId(), seekbar, new APSLifecycleKit.APSCallback() {

            @Override
            public void onServiceConnected(@Nullable ComponentName name, @Nullable IBinder iBinder) {
                super.onServiceConnected(name, iBinder);
                if (apsKit.isTaskPlaying()) {
                    KillMusicUtils.hideReadNewsWin();
                }
            }

            @Override
            public void onUpdateProgress(@Nullable IMediaPlayer mediaPlayer) {
                super.onUpdateProgress(mediaPlayer);
                currentPlayPosition.setText(APSLifecycleKit.turnTime((int) (mediaPlayer.getCurrentPosition() / 1000)));
            }

            @Override
            public void onBufferingUpdate(@Nullable IMediaPlayer mediaPlayer, int percent) {
                super.onBufferingUpdate(mediaPlayer, percent);
            }

            @Override
            public void onCompletion(@Nullable IMediaPlayer mediaPlayer) {
                super.onCompletion(mediaPlayer);
            }

            @Override
            public void onMetadataChanged(@Nullable MediaMetadata metadata) {
                super.onMetadataChanged(metadata);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onPlaybackStateChanged(@Nullable PlaybackState state) {
                super.onPlaybackStateChanged(state);
                switch (state.getState()) {

                    case PlaybackState.STATE_NONE://无任何状态
                    case PlaybackState.STATE_STOPPED:
                    case PlaybackState.STATE_PAUSED:
                        updateToggleDrawable(false);
                        break;
                    case PlaybackState.STATE_PLAYING:
                        updateToggleDrawable(true);
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_NEXT://下一首
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_PREVIOUS://上一首
                        break;
                    case PlaybackState.STATE_FAST_FORWARDING://快进
                        break;
                    case PlaybackState.STATE_REWINDING://快退
                        break;
                    case PlaybackState.STATE_ERROR:
                        com.utils.ToastUtil.showToastCenter(BaseAudioActivity.this, "出错了", Toast.LENGTH_SHORT);
                        break;
                }
            }

            @Override
            public void onPrepared(@Nullable IMediaPlayer mediaPlayer) {
                super.onPrepared(mediaPlayer);
                totoalLength.setText(APSLifecycleKit.turnTime((int) (mediaPlayer.getDuration() / 1000)));
            }
        });
        apsKit.setAutoPlay(isAutoPlay);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int widthPixels = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        float density = dm.density;
        if (getIntent().getBooleanExtra("ChatRoomOpen", false)) {
            audioStyle = AUDIO_STYLE_HALF_SCREEN;
            chatRoomOpen = true;
        } else {
            audioStyle = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getAudio_style();
        }

        Log.w(TAG, "onCreate  onCreate  density: " + density + "  widthPixels :" + widthPixels + "  heightPixels :" + heightPixels + "   " + audioStyle);
        super.onCreate(savedInstanceState);
        if (audioStyle == AUDIO_STYLE_HALF_SCREEN && !chatRoomOpen) {
            broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
            boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(AppFactoryGlobalConfig.getAppServerConfigInfo(this).getContent_list());
            if (isLeftImgMode) {
                for (int i = 0; i < 3; i++) {
                    broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
                }
            } else {
                for (int i = 0; i < 3; i++) {
                    broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
                }
            }
        }
        newsLikePresenter = new NewsLikePresenter(this, this);
        getArgs();
        initView();
        setArgs();
        initAPS();
        setNewsTitle();
        initNetStatusBroad();
        intPayViews();
        collectionController = new CollectionController(this, catalogItem, articleItem, this);
        if (articleItem != null) readStatus();
        initShare();
        setListener();

        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        apsKit.setAutoPlay(isAutoPlay);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        AppfacBuyEnableUtils.refresh(this, false);
        likeBadgeView.setArticleItem(articleItem);
        likeBadgeView.setLikeNum(articleItem);
        showPageTransition();
        if (chatRoomOpen) {
            TextView tvProgramButton = mRootView.findViewById(R.id.programListButton);

            tvProgramButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    //  openProgramList();
                    Intent intent = new Intent(BaseAudioActivity.this, ChatLiveProgressListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", articleItem);
                    bundle.putInt("COLOR", getPaletteColor());
                    bundle.putBoolean("fullScreen", true);
                    bundle.putBoolean("isPlay", apsKit.isPlaying());
                    bundle.putLong("START_LONG", startLong);
                    bundle.putLong("END_LONG", endLong);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    protected boolean needLoadTopBgSkin() {
        return false;
    }

    @Override
    public void updateLikesSuccess(AddLikeDataInvoke.AddLikeDataReciver data) {
        try {
            int likes = Integer.parseInt(likeBadgeView.getBadgeTextView().getText().toString());
            collectLike(!likeBadgeView.isSelected(), articleItem.getCatalogId() + "", articleItem.getId() + "");
            if (articleItem.getIsSupport()) {
                //点赞
                if (data.state) {
                    likes++;
                    likeBadgeView.setBadgeText(StringUtils.toTenThousand(String.valueOf(likes)));
//                    ToastUtil.show(this, R.string.dianzan_true);
                    if (AppFactoryGlobalConfig.getAppServerConfigInfo(this).cancelSupport == 0) {
                        likeBadgeView.setSelected(false);
                    } else {
                        likeBadgeView.setSelected(true);
                    }
                } else {
                    updateLikesFault(null);
                    return;
                }
            } else {
                //取消点赞s
                if (data.state) {
                    likes--;
                    likeBadgeView.setBadgeText(StringUtils.toTenThousand(String.valueOf(likes)));
//                    ToastUtil.show(this, R.string.dianzan_fase);
                    likeBadgeView.setSelected(false);
                } else {
                    updateLikesFault(null);
                    return;
                }
            }
            if (likes <= 0) {
                likeBadgeView.showBadgeText(false);
            } else {
                likeBadgeView.showBadgeText(true);
            }
            articleItem.setSupportCount(likes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateLikesFault(Object data) {
        if (likeBadgeView.isSelected()) {
            ToastUtil.show(this, R.string.cancel_dianzan_fase);
        } else {
            ToastUtil.show(this, R.string.dianzan_fail);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (articleItem != null) {
            collectionController.checkCollection();
            SupportKit.INSTANCE.initSupportViewState(this, SupportKit.TYPE_1, "" + articleItem.getId(),likeBadgeView);
        }
    }

    protected void initShare() {
//        sharePopWindow = new SharePopGridWindow(this);
//        sharePopWindow.setShareGirdListener(new ShareGirdItemListener());
//        shareGridDataUtil = new SBShareUtils();
//        shareGridDataUtil.initBaseShareGridData(this);
        shareWrap =new  ShareWrap(this,false);
        shareWrap.setShowFunction(true);
        shareWrap.init(articleItem,new CatalogItem());

    }

//    class ShareGirdItemListener implements OnItemClickListener {
//        @Override
//        public void onItemClick(AdapterView<?> parent, View view, int position,
//                                long id) {
//            ShareGridClickUtil.ShareGridClickHandle(shareGridDataUtil, position, articleItem, catalogItem, BaseAudioActivity.this);
//        }
//
//    }
    @Override
    public void updateLikesNum(int value) {

    }

    @SuppressWarnings("deprecation")
    protected void initView() {
        progressLayoutView = Utility.findViewById(mRootView, R.id.progress_layout);
        mBgImage = Utility.findViewById(mRootView, R.id.bgImage);
        seekbar = Utility.findViewById(mRootView, R.id.seekbar);
        playBtnContainer = Utility.findViewById(mRootView, R.id.playBtnContainer);
        letmeSayLayout = Utility.findViewById(mRootView, R.id.letmeSayLayout);
        mLoadingView = Utility.findViewById(mRootView, R.id.mLoadingView);
        // backgroundImage = Utility.findViewById(mRootView, R.id.backgroundImage);
        currentPlayPosition = Utility.findViewById(mRootView, R.id.currentPlayPosition);
        totoalLength = Utility.findViewById(mRootView, R.id.totoalLength);
        dotContainer = Utility.findViewById(mRootView, R.id.dotContainer);
        logoDot = Utility.findViewById(mRootView, R.id.logoDot);
        desDot = Utility.findViewById(mRootView, R.id.desDot);
        audioDesTitle = Utility.findViewById(mRootView, R.id.audioDesTitle);
        programBtn = Utility.findViewById(mRootView, R.id.programBtn);
        vodRelevant = Utility.findViewById(mRootView, R.id.vodRelevant);
        loopModeBtn = Utility.findViewById(mRootView, R.id.loopModeBtn);
        streamLineBtn = Utility.findViewById(mRootView, R.id.streamLineBtn);
//        audio_like_imageview = Utility.findViewById(mRootView, R.id.audio_like_imageview);
        likeBadgeView = Utility.findViewById(mRootView, R.id.like_badge_view);
        likeBadgeView.setNeedNewIcon(true);
        int mainColor = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getMainColor();
        mTitlebar_More.updateEffDrawable();
        collectionBtn = Utility.findViewById(mRootView, R.id.collectionBtn);
        //		commentInputView=Utility.findViewById(mRootView, R.id.commentInputView);

        letmeSay = Utility.findViewById(mRootView, R.id.letmeSay);
        if (!isFullScreen()) {
            TextView textView = (TextView) letmeSay;
            textView.setHintTextColor(0xFF999999);
        }
/*        badgeView = new BadgeView(this);
        badgeView.setTargetView(letmeSaybtn);
        badgeView.setBadgeCount(-7);*/

        commentsBadgeView = findViewById(R.id.badgeView_comments);
        commentsBadgeView.setBadgeTextBgColor(getResources().getDimensionPixelOffset(R.dimen.dimen8), Color.RED);
        commentsBadgeView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                intoComment();
            }
        });
        commentsBadgeView.setVisibility(View.VISIBLE);
        commentsBadgeView.showBadgeText(true);
        togglePauseBtn = Utility.findViewById(mRootView, R.id.togglePauseBtn);
        prev_audioBtn = Utility.findViewById(mRootView, R.id.prev_audioBtn);
        next_audioBtn = Utility.findViewById(mRootView, R.id.next_audioBtn);

        if (isFullScreen())
            mTitileBar.setBackgroundColor(Color.TRANSPARENT);
        // mBottom_shareBtn.setVisibility(View.GONE);
        openLikeBtn = articleItem != null && articleItem.getTagsflag() == 1 && AppFactoryGlobalConfig.getAppServerConfigInfo(this).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(this).getOtherFunction().getSupport() > 0;// "1".equals(getResources().getString(R.string.openLikeBtn));
        if (openLikeBtn) {
            likeBadgeView.setVisibility(View.VISIBLE);
        } else {
            likeBadgeView.showBadgeText(false);
            likeBadgeView.setVisibility(View.GONE);
        }
        setBackgroundImage();
        initHalfScreenView();
        initFullScreenView();
    }

    /**
     * @return 全屏返回true 否则false
     */
    protected boolean isFullScreen() {
        //服务器返回有问题，根据描述0是全屏，1是非全屏
        return audioStyle == AUDIO_STYLE_FULL_SCREEN;
    }

    protected void initFullScreenView() {
        if (!isFullScreen()) {
            return;
        }
        mTop_back.setImageResource(R.drawable.video_back);
        mTop_back.getLayoutParams().width = (int) getResources().getDimension(R.dimen.dimen10);
        mTop_back.getLayoutParams().height = (int) getResources().getDimension(R.dimen.dime_18);
        mTop_back.requestLayout();
        mTitlebar_More.setTint(Color.WHITE, Color.WHITE);
        mTitlebar_name.setTextColor(Color.WHITE);
        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
        fullImageBottomBg = Utility.findViewById(mRootView, R.id.bottom_bg_image);
        fullRelativeSwitch = Utility.findViewById(mRootView, R.id.relative_switch);
        fullImageGuide = Utility.findViewById(mRootView, R.id.image_guide);
        fullTvGuideInfo = Utility.findViewById(mRootView, R.id.tv_guide_info);
        fullRelativeInfo = Utility.findViewById(mRootView, R.id.relative_info);
        fullTopMaskView = Utility.findViewById(mRootView, R.id.view_top_mask);
        fullRelativeInfo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showFullRelativeInfo(!relativeInfoShow, true);
            }
        });
        fullTvGuideInfo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showFullRelativeInfo(!relativeInfoShow, true);
            }
        });
        fullRelativeSwitch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showFullRelativeInfo(!relativeInfoShow, true);
            }
        });
        likeBadgeView.setNormalColor(Color.WHITE);
        fullVoiceSeekBar = Utility.findViewById(mRootView, R.id.audio_voice_seekbar);
        audioMngHelper = new AudioMngHelper(this);
        audioMngHelper.setVoiceStep100(1);
        fullVoiceSeekBar.setProgress(audioMngHelper.get100CurrentVolume());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!isFullScreen()) {
            return super.onKeyDown(keyCode, event);
        }
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                int subCount = audioMngHelper.subVoice100();
                fullVoiceSeekBar.setProgress(subCount);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                int addCount = audioMngHelper.addVoice100();
                fullVoiceSeekBar.setProgress(addCount);
                return true;
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void showFullRelativeInfo(boolean show, boolean needAnimation) {
        relativeInfoShow = show;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (show) {
                Animation animation = new AlphaAnimation(0, 1);
                if (!needAnimation) {
                    animation.setDuration(10);
                } else {
                    animation.setDuration(300);
                }
                animation.setFillAfter(true);
                fullTopMaskView.startAnimation(animation);
                fullTopMaskView.setVisibility(View.VISIBLE);
            } else {
                Animation animation = new AlphaAnimation(1, 0);
                if (!needAnimation) {
                    animation.setDuration(10);
                } else {
                    animation.setDuration(300);
                }
                animation.setFillAfter(true);
                fullTopMaskView.startAnimation(animation);
                fullTopMaskView.setVisibility(View.GONE);
            }
        }
        if (show) {
            fullRelativeInfo.setVisibility(View.VISIBLE);
            if (needAnimation) {
                Animation animation = new AlphaAnimation(0, 1);
                animation.setDuration(300);
                fullRelativeInfo.startAnimation(animation);
            }
        } else {
            if (needAnimation) {
                Animation animation = new AlphaAnimation(1, 0);
                animation.setDuration(300);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        fullRelativeInfo.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                fullRelativeInfo.startAnimation(animation);
            } else {
                fullRelativeInfo.setVisibility(View.GONE);
            }
        }

    }


    protected void initHalfScreenView() {
        if (isFullScreen()) {
            return;
        }
        mBottom_shareBtn = Utility.findViewById(mRootView, R.id.mBottom_shareBtn);
        mBottom_shareBtn.setOnClickListener(this);
        mTitlebar_MoreContainer.setVisibility(View.VISIBLE);
        int moreImage = R.drawable.appfactory_top_more_img;
        mTitlebar_More.pressImg = mTitlebar_More.normalImg = ContextCompat.getDrawable(this, moreImage);
        mTitlebar_More.updateEffDrawable();
        renderTitleBarIconColor();
        tv_audio_title = Utility.findViewById(mRootView, R.id.tv_audio_title);
        collapsedTextView = Utility.findViewById(mRootView, R.id.collapsed_text);
        tvInfoTitle = Utility.findViewById(mRootView, R.id.tv_audio_title);
        componentLinear = Utility.findViewById(mRootView, R.id.linear_layout_relative_component);
        if (!chatRoomOpen)
            topicListDataInvoker = new TopicListDataInvoker(new DataInvokeCallBack<TopicDetailDataReciver>() {
                @Override
                public void success(TopicDetailDataReciver data) {
                    Log.w(TAG, "success");
                    //直播聊天室就不要组件了吧 都显示不完了
                    componentLinear.removeAllViews();
                    NewsDetailComponentUtils.addComponentList(componentLinear, data.componentItems, articleItem, BaseAudioActivity.this, getSupportFragmentManager(), 1);
                }

                @Override
                public void fault(Object data) {
                    Log.e(TAG, "fault");
                }
            });
        newTitleBgImage = Utility.findViewById(mRootView, R.id.image_title_bg);
        if (!chatRoomOpen) {
            Bitmap bitmap = BitmapUtil.zoomImage(getResources(), R.drawable.audio_play_small_btn_bg,
                    (int) getResources().getDimension(R.dimen.dimen_360dp), (int) getResources().getDimension(R.dimen.dime_150dp));
            bitmap = BitmapUtils.blurBitmap(this, bitmap, 25);
            newTitleBitmapDrawable = new BitmapDrawable(getResources(), bitmap);
            newTitleBgImage.setImageDrawable(newTitleBitmapDrawable);
        }
        imageToggleBg = Utility.findViewById(mRootView, R.id.image_toggle_bg);
        FunKt.load(imageToggleBg, AppFactoryGlobalConfig.getDefaultImageLoadDrawable());

        if (!chatRoomOpen) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) AppFactoryGlobalConfig.getDefaultImageLoadDrawable();
            Bitmap bitmap1 = Bitmap.createBitmap(bitmapDrawable.getBitmap());
            bitmap1 = BitmapUtils.blurBitmap(this, bitmap1, 25);
            newTitleBgImage.setImageBitmap(bitmap1);
        } else {
            if (!loadedImg) {
                setHalfTitleImage(articleItem.getLogo());
                FunKt.loadRound(imageToggleBg, articleItem.getLogo(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), null);
                loadedImg = true;
            }
        }

    }

    //  GlideUtils.GlideLoadListener loadListener;

    protected void setBackgroundImage() {
        if (!TextUtils.isEmpty(AppFactoryGlobalConfig.getAppServerConfigInfo(this).getAudioBgImage())) {

            if (mBgImage != null)
                FunKt.load(mBgImage, AppFactoryGlobalConfig.getAppServerConfigInfo(this).getAudioBgImage(), 0, null, new RequestListener<Drawable>() {

                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        FunKt.load(mBgImage, AppFactoryGlobalConfig.getAppServerConfigInfo(BaseAudioActivity.this).getAudioBgImage());
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                });
        }
    }

    @Override
    protected void moreClicked() {
        openShare();
    }


    private void setListener() {
        if (audioStyle != AUDIO_STYLE_HALF_SCREEN)
            mTitileBar.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    mTitileBar.getViewTreeObserver().removeOnPreDrawListener(this);
                    Rect outRect = new Rect();
                    getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
                    MarginLayoutParams layoutParams = (MarginLayoutParams) mTitileBar.getLayoutParams();
                    layoutParams.topMargin = outRect.top;
                    mTitileBar.setLayoutParams(layoutParams);
                    return true;
                }
            });

        seekbar.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                seekbar.getViewTreeObserver().removeOnPreDrawListener(this);
                setAboutSeekBarLayout();
                return true;
            }
        });
        collectionBtn.setOnClickListener(this);
        togglePauseBtn.setOnClickListener(this);
        streamLineBtn.setOnClickListener(this);
        letmeSay.setOnClickListener(this);
        programBtn.setOnClickListener(this);
        vodRelevant.setOnClickListener(this);
    }


    protected void showInputComment() {
//        commentDialogFram.articleItem = articleItem;
//        commentDialogFram.show(mRootView);
        CommentDialog.Companion.startActivity(this,articleItem,false,false);
    }

    /**
     * 设置与seekbar相关的布局 主要是SeekBar点的宽高问题 设置上下的一些边距之类的属性
     */
    private void setAboutSeekBarLayout() {
        if (seekbar.getSeekBarThumb() == null) {
            return;
        }
        MarginLayoutParams seekbarLayoutparam = (MarginLayoutParams) seekbar.getLayoutParams();
        seekbar.setLayoutParams(seekbarLayoutparam);

    }

    protected void getArgs() {
        Uri uriData = getIntent().getData();
        if (uriData != null) {
            isFromH5OpenToReStart =UriTool.INSTANCE.isFromH5OpenToReStart(this,uriData);
            String articleid = uriData.getQueryParameter("articleid");
            String title = uriData.getQueryParameter("title");
            String cname = uriData.getQueryParameter("cname");
            String tag = uriData.getQueryParameter("tag");
            catalogItem = new CatalogItem();
            catalogItem.setCatname(cname);
            articleItem = new ArticleItem();
            try {
                articleItem.setTitle(title);
                if (!TextUtils.isEmpty(articleid))
                    articleItem.setId(Long.valueOf(articleid));
            } catch (Exception e) {
            }
        } else {
            articleItem = getIntent().getParcelableExtra("data");
            catalogItem = getIntent().getParcelableExtra("catalog");
        }
        try {
            if (catalogItem == null)
                catalogItem = new CatalogItem();
            catalogItem.setCatalog_type(getIntent().getStringExtra("category"));
            catalogItem.setCatid(getIntent().getStringExtra("navigate_id"));
            if (articleItem == null) {
                articleItem = new ArticleItem();
                articleItem.setId(Long.parseLong(getIntent().getStringExtra("article_id")));
                articleItem.setSummary(getIntent().getStringExtra("summary"));
                articleItem.setTitle(getIntent().getStringExtra("title"));
                articleItem.setUrl(getIntent().getStringExtra("url"));
                articleItem.setIsAdvertisement(getIntent().getIntExtra("isAdvertisement", 0));
                articleItem.setIsBarrage(getIntent().getIntExtra("isBarrage", 0));
                articleItem.setReferSourceID(getIntent().getStringExtra("ReferSourceID"));
                articleItem.setIsComment(getIntent().getStringExtra("isComment"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        articleItem.chatRoomOpen = chatRoomOpen ? 1 : 0;
        showSwitch = articleItem.getmShowSwitch();
    }

    protected void setNewsTitle() {

        int base = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getBase();
        if (base == TitileType.FRAME) {
            setFrameTypeTitle();
        } else if (base == TitileType.NAVIGATE) {
            setTitle(catalogItem != null ? catalogItem.getCatname() : "");
        } else if (base == TitileType.NEWS_TITLE) {
            setTitle(articleItem != null ? articleItem.getTitle() : "");
        } else if (base == TitileType.NOTITLE) {
            setTitle("");
        }

    }

    protected void setArgs() {
        /*if (articleItem != null) {
            setTitle(articleItem.getTitle());
        }*/
        //badgeView.setText(articleItem.getCommentCount() + "");
        commentsBadgeView.setBadgeText(articleItem.getCommentCount() + "");
        if (articleItem.getCommentCount() > 0) {
            commentsBadgeView.showBadgeText(true);
        } else {
            commentsBadgeView.showBadgeText(false);
            commentsBadgeView.setBadgeTextViewGone();
        }
        if (TextUtils.isEmpty(articleItem.getSummary())) {
            if (!isFullScreen()) {
                audioDesTitle.setVisibility(View.GONE);
                if (!chatRoomOpen)
                    collapsedTextView.setText(getString(R.string.audio_no_summary));
            } else {
                fullTvGuideInfo.setText(getString(R.string.audio_no_summary));
            }
        } else {
            if (!isFullScreen()) {
                if (!chatRoomOpen)
                    collapsedTextView.setText(articleItem.getSummary());

//            collapsedTextView.setText("aaasdvdsv地址DVD发的说法飞得更高水电费梵蒂冈所多或过军或付军过过过过或军付军手动阀发阿发达速度韩国锦湖你好寂寞与建议就是个速度发的方式");
            } else {
                fullTvGuideInfo = Utility.findViewById(mRootView, R.id.tv_guide_info);
                fullTvGuideInfo.setText(articleItem.getSummary());
            }
        }
        if (isFullScreen()) {
            String imageUrl;
            if (articleItem.getMovie() == null || TextUtils.isEmpty(articleItem.getMovie().getAudioplayerImagePath())) {
                Log.e(TAG, "server error  articleItem.getMovie() is null ");
                imageUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getAudioBgImage();
            } else {
                imageUrl = articleItem.getMovie().getAudioplayerImagePath();
            }
            if (mBgImage != null) {
                FunKt.load(mBgImage, imageUrl);
                // GlideUtils.loadUrl(imageUrl, mBgImage, null, null, false, false, null);
            }
            FunKt.otherLoad(this, imageUrl, new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    try {
                        BitmapDrawable bitmapDrawable = (BitmapDrawable) resource;
                        likeBadgeView.setSelectedColor(DefaultBgUtil.getTintColor(BaseAudioActivity.this));
//                       if(likeBadgeView.isSelected()){
//                           likeBadgeView.setSelected(true);
//                       }else {
//                           likeBadgeView.setSelected(false);
//                       }
                        SupportKit.INSTANCE.initSupportViewState(BaseAudioActivity.this, SupportKit.TYPE_1, "" + articleItem.getId(), likeBadgeView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return false;
                }
            });

            RequestOptions options = new RequestOptions()
                    .transform(new BlurTransformation(this, 25, 15));
            FunKt.load(fullImageBottomBg, imageUrl, options);
            showFullRelativeInfo(false, false);
        }

        if ("0".equals(articleItem.getIsComment()) || AppFactoryGlobalConfig.getAppServerConfigInfo(this).getIs_member() <= 0) {
            letmeSayLayout.setVisibility(View.GONE);
        } else {
            letmeSayLayout.setVisibility(View.VISIBLE);
        }
        collectionController = new CollectionController(this, catalogItem, articleItem, this);
        updateCollectionStatus();
        SupportKit.INSTANCE.initSupportViewState(this, SupportKit.TYPE_1, "" + articleItem.getId(),  likeBadgeView);
        articleItem.chatRoomOpen = chatRoomOpen ? 1 : 0;
    }

    /**
     * 这种你好的操作，后面需要优化
     */
    protected void setHalfTitleImage(final String imageAddress) {
        new Thread(new Runnable() {
            Bitmap bitmap = null;

            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(imageAddress);
                    InputStream is = null;
                    BufferedInputStream bis = null;
                    try {
                        is = url.openConnection().getInputStream();
                        bis = new BufferedInputStream(is);
                        bitmap = BitmapFactory.decodeStream(bis);
//                        bitmap = BitmapUtils.scaleBitmap(bitmap, (int) getResources().getDimension(R.dimen.dimen_360dp), (int) getResources().getDimension(R.dimen.dime_150dp));
                        bitmap = BitmapUtils.blurBitmap(BaseAudioActivity.this, bitmap, 15);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (chatRoomOpen) {
                                    bgColorFromBitmap = getBigColor(bitmap);
                                    newTitleBgImage.setBackgroundColor(bgColorFromBitmap);
                                } else {
                                    newTitleBgImage.setImageBitmap(bitmap);
                                }
                            }
                        });
                        bis.close();
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取组件的相关数据
     */
//    protected void getComponentData() {
//        if (!isFullScreen()) {
//            /*int base = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getBase();
//            if (base == TitileType.FRAME) {
//            } else if (base == TitileType.NAVIGATE) {
//                tv_audio_title.setText(catalogItem != null ? catalogItem.getCatname() : "");
//            } else if (base == TitileType.NEWS_TITLE) {
//                tv_audio_title.setText(articleItem != null ? articleItem.getTitle() : "");
//            } else if (base == TitileType.NOTITLE) {
//                tv_audio_title.setText("");
//            }*/
//            tv_audio_title.setText(articleItem.getTitle());
//            if (articleItem.getCid() > 0) {
//                topicListDataInvoker.getTopicDetailById(String.valueOf(articleItem.getCid()), pageNum, pageSize);
//            } else {
//
//                topicListDataInvoker.getArticleById(String.valueOf(articleItem.getId()), UserInfo.getUserInfo(this).getUserid(), articleItem.getParentId(), pageNum, pageSize);
//            }
//
//        }
//    }

    protected void updateCollectionStatus() {
        if (collectionController != null)
            collectionController.checkCollection();
    }

    /**
     * 收藏
     */
    protected void collectionAction() {
        collectionController.collection();
    }

    /**
     * 进入登录
     *
     * @param context
     */
    protected void intoLogin(Context context) {
//        ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source="音频";
        LoginUtils.invokeLogin(context);
//        Intent intent = new Intent();
//        intent.setClassName(context, ModuleReferenceConfig.LoginActivity);
//        context.startActivity(intent);
    }

    @Override
    public int getLayoutResID() {
        switch (audioStyle) {
            case AUDIO_STYLE_FULL_SCREEN:
                return R.layout.aappfactory_activity_audio_basepage;
            case AUDIO_STYLE_HALF_SCREEN:
                if (chatRoomOpen) {
                    return R.layout.app_factory_activity_audio_player_chat;
                } else {
                    return R.layout.app_factory_activity_audio_player;
                }
            default:
                audioStyle = AUDIO_STYLE_FULL_SCREEN;
                return R.layout.aappfactory_activity_audio_basepage;
        }
    }

    @Override
    protected final boolean getFitSystemWindow() {
        if (audioStyle == AUDIO_STYLE_HALF_SCREEN)
            return super.getFitSystemWindow();
        return false;
    }

    @Override
    public void refreshStatusBarColor() {
        if (audioStyle == AUDIO_STYLE_HALF_SCREEN) {
            super.refreshStatusBarColor();
            return;
        }
        StatusBarUtil.setTransparentForWindow(this);
    }

    @Override
    public final int getStatusBarColor() {
        if (audioStyle == AUDIO_STYLE_HALF_SCREEN)
            return super.getStatusBarColor();
        return Color.TRANSPARENT;
    }

    protected boolean needLoadTopSkin() {
        return false;
    }

    /**
     * 网络状态改变时候的Dialog
     *
     * @param noticType
     */
    private boolean isCloseNetQuest;
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.letmeSaybtn) {
            intoComment();
        } else if (v.getId() == R.id.letmeSay) {
            if (isFullScreen()) {
                intoComment();
            } else {
                showInputComment();
            }
        } else if (v.getId() == R.id.collectionBtn) {
            collectionBtn.setEnabled(false);
            collectionAction();
        } else if (v.getId() == R.id.programBtn || v.getId() == R.id.vodRelevant) {
            openProgramList();
        } else if (v.getId() == R.id.togglePauseBtn) {
            KillMusicUtils.hideReadNewsWin();
            if (isCloseNetQuest) {
                checkNetType();
                return;
            }
            onToggleClick();
            apsKit.toggle();
        } else if (v.getId() == R.id.streamLineBtn) {
            showStreamLine();
        } else if (v.getId() == R.id.mBottom_shareBtn) {
            openShare();
        }
    }

    public void onToggleClick() {

    }


    abstract void showStreamLine();

    /**
     * 显示收藏按钮的状态
     *
     * @param collected
     */
    protected void showCollectionBtnStatus(boolean collected) {
        if (collected) {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.common_collected);
            Drawable bitmapDrawable = new BitmapDrawable(getResources(), bmp);
            if (isFullScreen()) {
                bitmapDrawable = tintDrawable(R.drawable.common_collected, DefaultBgUtil.getTintColor(this));
            }
            collectionBtn.normalImg = bitmapDrawable;
            collectionBtn.pressImg = bitmapDrawable;
        } else {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.common_un_collect);
            Drawable bitmapDrawable = new BitmapDrawable(getResources(), bmp);
            if (isFullScreen()) {
                bitmapDrawable = tintDrawable(R.drawable.common_un_collect, Color.WHITE);
            }
            collectionBtn.normalImg = bitmapDrawable;
            collectionBtn.pressImg = bitmapDrawable;
        }
        collectionBtn.updateEffDrawable();
    }

    protected Drawable tintDrawable(int drawableId, @ColorInt int color) {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), drawableId);
        Drawable bitmapDrawable = new BitmapDrawable(getResources(), bmp);
        bitmapDrawable = Utility.tintDrawable(color, bitmapDrawable.mutate());
        return bitmapDrawable;
    }

    protected int getPaletteColor() {
//        if (palette == null) {
//            return Color.RED;
//        }
//        return palette.getVibrantColor(Color.RED);
        return bgColorFromBitmap;
    }


    /**
     * 取图片中的主色
     *
     * @param bitmap
     * @return
     */
    public static int getBigColor(Bitmap bitmap) {
        ArrayList<Integer> picturePixel = getPicturePixel(small(bitmap));
        //计数相同颜色数量并保存
        HashMap<Integer, Integer> color2 = new HashMap<>();
        for (Integer color : picturePixel) {
            if (color2.containsKey(color)) {
                Integer integer = color2.get(color);
                integer++;
                color2.remove(color);
                color2.put(color, integer);

            } else {
                color2.put(color, 1);
            }
        }
        //挑选数量最多的颜色
        Iterator iter = color2.entrySet().iterator();
        int count = 0;
        int color = 0;
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            int value = (int) entry.getValue();
            if (count < value) {
                count = value;
                color = (int) entry.getKey();
            }

        }
        return color;
    }

    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.25f, 0.25f);
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    public static ArrayList<Integer> getPicturePixel(Bitmap bitmap) {

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 保存所有的像素的数组，图片宽×高
        int[] pixels = new int[width * height];

        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

        ArrayList<Integer> rgb = new ArrayList<>();
        for (int i = 0; i < pixels.length; i++) {
            int clr = pixels[i];
            int red = (clr & 0x00ff0000) >> 16; // 取高两位
            int green = (clr & 0x0000ff00) >> 8; // 取中两位
            int blue = clr & 0x000000ff; // 取低两位
//            Log.w("tag", "r=" + red + ",g=" + green + ",b=" + blue);
            int color = Color.rgb(red, green, blue);
            //除去白色和黑色
            if (color != Color.WHITE && color != Color.BLACK) {
                rgb.add(color);
            }
        }

        return rgb;
    }

    /**
     * 打开分享
     */
    private void openShare() {

       // sharePopWindow.setShareGridAdaptorData(shareGridDataUtil.BaseShareGridData);
        shareWrap.show(mRootView);
    }

    protected void intoComment() {
        Intent intent = new Intent();
        intent.putExtra("data", articleItem);
        intent.setClass(this, XCommentActivity.class);
        startActivity(intent);
    }

    /**
     * 打开节目单或是点播清单 子类去实现
     */
    abstract void openProgramList();

    protected void updateToggleDrawable(boolean isPlay) {
        Drawable toggleDrawable;
        if (isPlay) {
            toggleDrawable = isFullScreen() ? getResources().getDrawable(R.drawable.audio_pausbtn) : getResources().getDrawable(R.drawable.audio_play_pause_btn);
        } else {
            toggleDrawable = isFullScreen() ? getResources().getDrawable(R.drawable.audio_playbtn) : getResources().getDrawable(R.drawable.audio_play_btn);
        }
        togglePauseBtn.normalImg = togglePauseBtn.pressImg = toggleDrawable;
        togglePauseBtn.updateEffDrawable();
    }


    protected final void sendShowFloaWinMsg() {
        if (PermissionUtils.checkPermission(this)) {
            startReadNews();
        }
    }

    //开启语音播报
    private void startReadNews() {
        if (TextUtils.isEmpty(apsKit.getUrl())) {
            return;
        }
        TXReportManager.getInstance().voice_read(articleItem);
        articleItem.setText_audio_url(apsKit.getUrl());
        if(apsKit.isTaskPlaying()){
            AudioFloatManager.Companion.getInstance(this).setArticle(articleItem);
            AudioFloatManager.Companion.getInstance(this).setCatalogItem(catalogItem);
        }
        AudioFloatManager.Companion.getInstance(this).show();

    }


    @Override
    public void finish() {
        super.finish();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (newsLikePresenter != null && newsLikePresenter.addLikeDataInvoke != null) {
            newsLikePresenter.addLikeDataInvoke.destory();
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;

        }
//        if (commentDialogFram != null) {
//            commentDialogFram.dismiss();
//            commentDialogFram.destory();
//        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == MemberActivity.REQUEST_CODE && intent != null
                && intent.getBooleanExtra(MemberActivity.REQUEST_KEY, false)) {
            normalPayUtil.judgeShowPayView(articleItem);
        }
    }


    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    protected NetChangeReceiver receiver;


    protected void initNetStatusBroad() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetChangeReceiver();
        registerReceiver(receiver, intentFilter);
    }

    protected class NetChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkNetType();
        }
    }

    /**
     * 检查网络状态
     */
    public void checkNetType() {
        PermissionUtil.INSTANCE.invokeNetWorkPermission(this, new IPermissionsAgree() {
            @Override
            public void onAgree() {
                extracted();

            }

            @Override
            public void onRefuse() {

            }

            @Override
            public void hasPermissions() {
                extracted();

            }
        });
    }

    private void extracted() {
        ConnectivityManager cm = SystemServiceManager.getConnectivityManager(this);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        //有網絡
        if (networkInfo != null && networkInfo.isAvailable()) {
            //目前變成手機流量狀態
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                netChangeStopPlay();
                showNoticeDialog(TYPE_NOT_WIFI);
                //目前變成手機WiFi狀態
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                netChangePlay();
            }
        } else {
            //沒網絡的時候
            netChangeStopPlay();
            showNoticeDialog(TYPE_NO_NETWORK);
        }
    }

    /**
     * 子类重写
     */
    public void netChangeStopPlay() {
        if (apsKit.isPlaying()) {
            apsKit.toggle();
        }
    }

    /**
     * 子类重写
     */
    public void netChangePlay() {

    }

    void showNoticeDialog(int noticType) {

        if (dialog != null && dialogType == noticType && dialog.isShowing()) {
            return;
        }
        dialogType = noticType;
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.audio_notic, null);
        TextView title = contentView.findViewById(R.id.audio_notice_title);
        TextView btn1 = contentView.findViewById(R.id.audio_notice_btn1);
        TextView btn2 = contentView.findViewById(R.id.audio_notice_btn2);
        dialog = null;
        dialog = new Dialog(this, R.style.loadingDialogStyle);
        dialog.setContentView(contentView);
        // 无网络提示
        if (noticType == TYPE_NO_NETWORK) {
            title.setText(R.string.audio_notice_noNetWork);
            btn1.setText(R.string.audio_notice_Got_it);
            btn2.setText(R.string.audio_notice_Go_check);
            btn1.setOnClickListener(v -> {
                isCloseNetQuest = true;
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            btn2.setOnClickListener(v -> {
                isCloseNetQuest = false;
                Intent intent = null;
                intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(intent);
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            // Wifi变流量
        } else if (noticType == TYPE_NOT_WIFI) {
            title.setText(R.string.audio_notice_isNotWifi);
            btn1.setText(R.string.audio_notice_goON);
            btn2.setText(R.string.audio_notice_close);
            btn1.setOnClickListener(v -> {
                isCloseNetQuest = false;
                netChangePlay();
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
            btn2.setOnClickListener(v -> {
                isCloseNetQuest = true;
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
        }
        dialog.show();
    }

    /**
     * 音频 不变色   变
     */
    @Override
    protected void renderTitleBarIconColor() {
        if (isFullScreen()) {
            return;
        }
        super.renderTitleBarIconColor();
    }


    @Override
    public void onCollectionStatus(String sourceId, boolean isCollection) {

        collectionBtn.setEnabled(true);
        showCollectionBtnStatus(isCollection);
    }

    @Override
    public void onCollectionOk(String sourceId, boolean isCollection, String msg) {
        collectionBtn.setEnabled(true);
        showCollectionBtnStatus(isCollection);
    }

    @Override
    public void onCollectionErr(String msg) {
        collectionBtn.setEnabled(true);
    }

    abstract protected void onPaidAudio(String audio);

    /**
     * 以下是付费相关的
     */
    //收费收听需要隐藏的布局
    protected RelativeLayout playPanelLayout;
    protected TextView payAmount;
    protected NormalPayUtil normalPayUtil;
    protected TextView tvVipPayHowmuch;

    private void intPayViews() {
        payAmount = Utility.findViewById(mRootView, R.id.pay_how_much);
        tvVipPayHowmuch = Utility.findViewById(mRootView, R.id.tv_vip_pay_how_much);
        GradientDrawable gradientDrawable = (GradientDrawable) tvVipPayHowmuch.getBackground();
        gradientDrawable.setCornerRadius(90);
        gradientDrawable.setGradientRadius(90);
        if (isFullScreen()) {
            gradientDrawable.setColor(0x0086715F);
            gradientDrawable.setStroke((int) getResources().getDimension(R.dimen.dimen1), Color.WHITE);
        }
        payAmount.setBackground(gradientDrawable);
        tvVipPayHowmuch.setBackground(gradientDrawable);
        playPanelLayout = Utility.findViewById(mRootView, R.id.playPanelLayout);
        normalPayUtil = new NormalPayUtil(this, catalogItem, new NormalPayUtil.Others() {

            @NotNull
            @Override
            public TextView getVipPayView() {
                return tvVipPayHowmuch;
            }

            @NotNull
            @Override
            public String operation() {
                return getString(R.string.pay_buy_audio);
            }

            @Override
            public List<View> payView() {
                List<View> payView = new ArrayList<>();
                payView.add(payAmount);
                return payView;
            }

            @Override
            public List<View> paidView() {
                List<View> paidView = new ArrayList<>();
                paidView.add(playPanelLayout);
                List<View> otherListPaidView = getPaidViews();
                if (otherListPaidView != null && otherListPaidView.size() != 0) {
                    paidView.addAll(otherListPaidView);
                }
                return paidView;
            }

            @NotNull
            @Override
            public TextView openView() {
                return payAmount;
            }
        }, new PaidContentListener() {
            @Override
            public void onPaidContent(@NotNull final PaidMetas meta) {
                onPaidAudio(meta.getAudio());
            }
        }, true);

    }

    /**
     * 获取其余支付后需要显示的View
     */
    protected List<View> getPaidViews() {
        return null;
    }
}